import React, { useEffect, useRef, useState } from 'react'
import { Form, Input, Button, Toast } from 'antd-mobile'
import InputPass from './InputPass';
import { ShowMsg, ShowSuccess } from '../utils/message';
import { useNavigate, useNavigation, useSearchParams, Link } from 'react-router-dom';
import { useCountDown, useLocalStorageState } from 'ahooks'
import { Ajax } from './../api/api';
import { reg } from '../utils/validate';
import useTimeDown from './../hooks/TimeDown';
import { ShowError } from '../utils/message';
import { useSelector } from 'react-redux';

const LoginByPhone = () => {
    const [query] = useSearchParams()
    const [form] = Form.useForm()
    const [toggle, setToggle] = useState<boolean>(true)
    const time = 180;
    const router = useNavigate()
    const fromPath = useSelector((state: any) => state.data.fromPath)
    const [targetDate, setTargetDate] = useState<number>();
    const [countdown] = useCountDown({
        targetDate,
        onEnd: () => {
            setToggle(true)
        }
    });

    const [disabled, setDisabled] = useState<boolean>(false)
    const todoSendCaptcha = async () => {
        let res = await Ajax.checkPhone({
            phone: form.getFieldValue('phone')
        }) as any;
        if (res.code == 200) {
            let res2 = await Ajax.sendCaptcha({
                phone: form.getFieldValue('phone')
            }) as any;
            if (res2.data) {
                ShowSuccess('验证码发送成功')
                setToggle(false)
                setTargetDate(Date.now() + time * 1000)
            }
        }
    }
    const [appaccount, setAppAccount] = useLocalStorageState<string | number | undefined>(
        'appaccount',
    );
    const [appToken, setAppToken] = useLocalStorageState<string | number | undefined>(
        'appToken',
    );
    const [appPhone, setAppPhone] = useLocalStorageState<string | number | undefined>(
        'appPhone',
    );

    const phoneChange = (value: any) => {
        setDisabled(reg.phone.test(value))
    }

    const todoCheckSubmit = () => {
        form.validateFields()
            .then(async (value: any) => {
                console.log(value)
                let res = await Ajax.checkPhone({
                    phone: value.phone
                }) as any;
                if (res.code == 200) {
                    let res2: any = await Ajax.verifyCaptcha(value).catch(err => {
                        Toast.show({
                            icon: 'fail',
                            content: '验证码校验失败',
                            duration: 1000,
                        })
                    })
                    if (res2.data) {
                        let res3 = await Ajax.gettoken({
                            phone: res.result.phone,
                            username: res.result.username,
                            password: res.result.password,
                        }) as any;
                        if (res3.code == 200) {
                            console.log(fromPath)
                            var fromName = fromPath.length >= 2 ? fromPath[fromPath.length - 2] : '';
                            if (fromName == '/reg' || fromName == '/findpass') {
                                router('/app/mine')
                            } else {
                                router(-1)
                            }

                            router('/app/mine')

                            setAppAccount(res.result.username)
                            setAppPhone(res.result.phone)
                            sessionStorage.setItem('appToken', res3.token)
                        }
                    }
                }
            })
            .catch(err => {
                Toast.show({
                    icon: 'fail',
                    content: '登录数据信息校验失败',
                    duration: 1000,
                })
            })
    }


    useEffect(() => {
        if (query.get('phone')) {
            form.setFieldValue('phone', query.get('phone'))
        } else {
            form.setFieldValue('phone', appPhone)
        }

        setDisabled(reg.phone.test(form.getFieldValue('phone')))
    }, [])


    return (
        <div className='pd10'>
            <Form
                form={form}
                layout={'horizontal'}
                initialValues={{

                }}
                footer={
                    <div>
                        <Button block onClick={todoCheckSubmit} color='success' size='middle'>
                            验证登录
                        </Button>
                        <Button block type='reset' className='mt10' color='danger' size='middle'>
                            重置
                        </Button>
                    </div>
                }
            >
                <Form.Header>手机号验证码登录~</Form.Header>
                <Form.Item
                    name='phone'
                    label='手机号'
                    rules={[
                        { required: true },
                        { pattern: reg.phone, message: '请输入正确的手机号' }
                    ]}

                >
                    <Input placeholder='请输入' clearable onChange={phoneChange} />
                </Form.Item>
                <Form.Item
                    name='captcha'
                    label='验证码'
                    rules={[
                        { required: true },
                        { pattern: reg.code, message: '请输入4位数字验证码' }
                    ]}
                    extra={
                        <div className='size10'>
                            {
                                toggle ?
                                    <Button disabled={!disabled} size={'small'} color='warning' onClick={todoSendCaptcha}  >发送验证码</Button>
                                    :
                                    <span>剩余{Math.floor(countdown / 1000)}S</span>
                            }
                        </div>
                    }
                >
                    <Input placeholder='请输入' clearable />
                </Form.Item>

                <Form.Item >
                    <div className="links flex ">
                        <Link to='/reg' className='link1'>注册账号</Link>
                        <Link to='/findpass' className='color2'>找回密码</Link>
                    </div>
                </Form.Item>
            </Form>
        </div>
    )
}

export default LoginByPhone